package com.fare.taluo.io.excel;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import jxl.Workbook;
/**
 * 一个实现基础Excel文件导入的抽象
 * @author xiangsf 2013-05-12
 *
 */
public abstract class ImportExcelClassic implements IImportExcel {

	protected Workbook wb = null;
	@Override
	public Object readExcel(InputStream is) throws ExcelImportException{
		try {
			com.fare.taluo.util.Assert.Assert.notNull(is, "传入的文件输入流为空!");
			wb = Workbook.getWorkbook(is);
			if(validateData())
				return this.importData();
		} catch (Exception e) {
			e.printStackTrace();
			throw new ExcelImportException("导入Excel出错!" ,e);
		}finally{
			if(wb != null) wb.close();
			wb = null;
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			is = null;
		}
		return true;
	}
	/**
	 * 导入数据
	 */
	protected abstract Object importData() throws ExcelImportException;
	/**
	 * 验证数据
	 * @return
	 */
	protected abstract boolean validateData() throws ExcelImportException;
	@Override
	public Object readExcel(File file) throws ExcelImportException{
		InputStream is = null;
		try {
			com.fare.taluo.util.Assert.Assert.notNull(file, "传入的文件为空!");
			is = new FileInputStream(file);
			wb = Workbook.getWorkbook(is);
			if(validateData())
				return this.importData();
		} catch (Exception e) {
			e.printStackTrace();
			throw new ExcelImportException(e.getMessage());
		}finally{
			if(wb != null) wb.close();
			wb = null;
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			is = null;
		}
		return true;
	}

}
